<?php
/**
 * MySQLDatabaseConnection handling MySQL database connection
 * @package Core
 * @subpackage Database
 * @author kovacsricsi
 */
class MySQLDatabaseConnection implements IDatabaseConnection
{
	/**
	 * Connection.
	 * @access public
	 * @static
	 */
	public static $connections = array();

	/**
	 * Get connection status.
	 * @access public
	 * @static
	 * @param string $name
	 * @return boolen
	 */
	public static function getConnectionStatus($name = "default")
	{
		if (!isset(self::$connections[$name])) {
			return false;
		} else {
			return true;
		}
	}

	/**
	 * Execute query.
	 * @access public
	 * @static
	 * @param string $query
	 * @param string $name
	 * @return resource
	 */
	public static function executeQuery($query, $name = "default")
	{
		self::checkConnection($name);

		$resp = mysql_query($query, self::$connections[$name]);

		return $resp;
	}

	/**
	 * Create connection.
	 * @access public
	 * @static
	 * @param string $name
     * @throws DatabaseErrorException
	 * @return void
	 */
	public static function createConnection($name = "default")
	{
		self::$connections[$name] = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

		if (self::$connections[$name]) {
			mysql_select_db(DB_NAME, self::$connections[$name]);

			self::executeQuery("SET NAMES " . DB_CHARSET);
		} else if (!is_resource(self::$connections[$name])) {
			throw new DatabaseErrorException($name);
		}
	}

	/**
	 * Check for existed connection.
	 * @access public
	 * @static
	 * @param string $name
	 * @return void
	 */
	public static function checkConnection($name)
	{
		if (!self::getConnectionStatus($name)) {
			self::createConnection($name);
		}
	}

	/**
	 * Protect database from sqlinjection.
	 * @access public
	 * @static
	 * @param string $string
	 * @return string
	 */
    public static function prepare($string)
    {
		if (!self::getConnectionStatus()) {
			self::createConnection();
		}
        
        return mysql_real_escape_string($string);
    }
}
?>